<?php
declare (strict_types=1);

namespace app\command;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class DirectC2 extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('directc2')
            ->setDescription('the c2 command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 交换机名
        $exchange = 'direct_logs';

        // 建立连接
        $connection = new AMQPStreamConnection('127.0.0.1', '5672', 'guest', 'guest', '/');
        // 获取信道
        $channel = $connection->channel();
        // 声明交换机
        $channel->exchange_declare($exchange, 'direct', false, false, false);

        // 声明创建队列
        // 队列名称为空时，会生成一个随机名称队列
        [$queue, ,] = $channel->queue_declare('', false, false, true, false);

        // 绑定交换机与队列，并指定路由info
        $channel->queue_bind($queue, $exchange, 'info');
        // 绑定交换机与队列，并指定路由error
        $channel->queue_bind($queue, $exchange, 'error');
        // 绑定交换机与队列，并指定路由warning
        $channel->queue_bind($queue, $exchange, 'warning');

        // 消息消费
        $channel->basic_consume($queue, '', false, false, true, false, function ($msg) use ($output) {
            // 模拟耗时
            sleep(3);
            $output->writeln('receive:' . $msg->body . PHP_EOL);
            // 确认消息处理完成
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        });

        while (count($channel->callbacks)) {
            $channel->wait();
        }

        // 关闭信道
        $channel->close();
        // 关闭连接
        $connection->close();
    }
}
